/**
 * 系统后台数据库连接配置JS-systemDataSource.jsp
 */

//项目路径
var strPath = window.document.location.pathname;
//var postPath = strPath.substring(0, strPath.substr(1).indexOf('/') + 1);
var postPath = "/gdp";
var editStart = 1;//1添加、2修改
$(function () {
    getServerType();
    getProjectSelect();
    getAllDatabase();
    $("#hid_a_pcode").val(GetQueryString("a_pcode"));

    //默认选中的项目工程
    if ($("#hid_a_pcode").val() != "null") {
        $("#ptype").val($("#hid_a_pcode").val());
    }
    retrunIndex();
    //数据列表
    $("#tb_dataList").bootstrapTable({
        url: postPath + '/system/sysprjService/getPrjServiceData',
        undefinedText: '-',
        pagination: true, // 分页
        striped: true, // 是否显示行间隔色
        queryParams: queryParams,
        cache: false, // 是否使用缓存
        pageList: [5, 10, 20],
        toolbar: "",// 指定工具栏
        showColumns: false, // 显示隐藏列
        showRefresh: false, // 显示刷新按钮
        uniqueId: "guid", // 每一行的唯一标识
        sidePagination: "server", // 服务端处理分页
        responseHandler: function (res) {
            return {
                "total": res.data.total,//总页数
                "rows": res.data.rows   //数据
            };
        },
        columns: [{
            field: 'state',
            checkbox: true,
            align: 'center',
            valign: 'middle'
        }, {
            title: '服务编码',
            field: 'servicecode', // 字段
            align: 'left', // 对齐方式（左 中 右）
            halign: 'center', // 对齐方式（左 中 右）
            valign: 'middle', //
            sortable: false
        }, {
            title: '服务名称',
            field: 'servicename',
            align: 'left', // 对齐方式（左 中 右）
            halign: 'center', // 对齐方式（左 中 右）
            valign: 'middle',
            sortable: false,
            cellStyle: function (value, row, index) {
                return {
                    css: {
                        "min-width": "40px",
                        "white-space": "nowrap",
                        "text-overflow": "ellipsis",
                        "overflow": "hidden",
                        "max-width": "120px"
                    }
                }
            },
            formatter: function (value, row, index) {
                return handColumnTip(value);
            }
        }, {
            title: '服务类型',
            field: 'servertype',
            align: 'center',
            valign: 'middle',
            sortable: false
        }, {
            title: '所属数据库',
            field: 'databaseName',
            align: 'center',
            valign: 'middle',
            sortable: false
        }, {
            title: '所属项目',
            field: 'projectname',
            align: 'center',
            valign: 'middle',
            sortable: false
        },{
	        title : '服务状态',
	        field : 'status',
	        align : 'center',  
	        valign : 'middle',  
	        sortable : false,
            formatter: function (value, row, index) {
                if (value == 1) {
                    return '启用'
                } else {
                    return '禁用'
                }
            }
	    },{
            title: '操作',
            align: 'center',
            valign: 'middle',
            sortable: false,
            formatter: function (value, row, index) {
                var strtd = "";
                //strtd+="<a href='javascript:;' onclick='addClick();' class='btn btn-default btn-sm'><i class='fa fa-plus'></i></a>";
                strtd += "<a href='javascript:;' title='编辑' onclick='updatepServerClick(\"" + row.servicetype + "\",\"" + row.servicecode + "\",\"" + row.pcode + "\");' class='btn btn-default btn-sm'><i class='fa fa-edit'></i> </a> ";
                //启用，禁用
                if (row.status == 1) {
                    strtd += "<a href='javascript:;' title='禁用服务' onclick='updateServerStatus(\"" + row.guid + "\", 0);' class='btn btn-default btn-sm'><i class='fa fa-eye-slash'></i> </a> ";
                } else {
                    strtd += "<a href='javascript:;' title='启用服务' onclick='updateServerStatus(\"" + row.guid + "\", 1);' class='btn btn-default btn-sm'><i class='fa fa-eye'></i> </a> ";
                }
                //授权
                // strtd += "<a href='javascript:;' title='授权' onclick='authService(\"" + row.guid + "\");' class='btn btn-default btn-sm'><i class='fa fa-asterisk'></i> </a> ";
                //调用方配置
                strtd += "<a href='javascript:;' title='调用方配置' onclick='configAccessCondition(\"" + row.guid + "\",\"" + row.servicetype + "\");' class='btn btn-default btn-sm'><i class='fa fa-server'></i> </a> ";

                strtd += " <a href='javascript:;' title='预览' onclick='previewServerClick(\"" + row.servicetype + "\",\"" + row.servicecode + "\");' class='btn btn-default btn-sm'><i class='fa fa-send'></i> </a>";

                return strtd;
            }
        }]
    });

    //查询操作
    $("#btn_Search").click(function () {
        $("#tb_dataList").bootstrapTable('refresh');
    });

    //刷新操作
    $("#btn_ref").click(function () {
        $("#tb_dataList").bootstrapTable('refresh');
    });

    //删除数据
    $("#btn_del").click(function () {
        // here row = rowList
        var row = $('#tb_dataList').bootstrapTable('getSelections');
        if (row == null || row == "" || row.length < 1) {
            bootbox.alert("请选择一行!");
            return;
        }

        deleteServerClick(row);
    });

    //添加操作
    $("#btn_add").click(function () {
        $("input[name='servicetype']:checked").removeAttr('checked')
        //cleanContent();
        /*var project = $("#ptype").val();
        if(project== ""){
            bootbox.alert("请选择项目工程!");
            return;
        }*/
        $("#EditContent").modal('show');
        editStart = 1;
    });

    //修改操作
    $("#btn_edit").click(function () {
        //cleanContent();
        var row = $('#tb_dataList').bootstrapTable('getSelections');
        if (row == null || row == "") {
            bootbox.alert("请选择一行!");
            return;
        } else if (row.length > 1) {
            bootbox.alert("请选择一行!");
            return;
        }

        $.ajax({
            type: 'POST',
            url: postPath + '/system/sysprjService/getServerByGuid',
            async: false,
            data: {guid: row[0].servicetype},
            dataType: 'json',
            success: function (res) {
                if (res != null) {
                    $(window.parent.document).find("#sysIframe").attr("src", res.pageurl + "?servercode=" + row[0].servicecode + "&projectid=" + row[0].pcode + "&operate=edit");
                } else {
                    bootbox.alert("服务不存在!");
                }
            }
        });

    });

    //保存数据
    $("#btn_save").click(function () {
        if (editStart == 1) {
            var server = $("input[name='servicetype']:checked").val();
            if ($("#projectcode").val() == "") {
                bootbox.alert("请选择项目工程!");
                return;
            }
            if (server == "" || server == undefined) {
                bootbox.alert("请选择服务类型!");
                return;
            }
            var project = $("#projectcode").val();
            $.ajax({
                type: 'POST',
                url: postPath + '/system/sysprjService/getServerByGuid',
                async: false,
                data: {guid: server},
                dataType: 'json',
                success: function (res) {
                    if (res != null) {
                        $(window.parent.document).find("#sysIframe").attr("src", res.pageurl + "?servertype=" + server + "&projectid=" + project + "&operate=add");
                    } else {
                        bootbox.alert("服务不存在!");
                    }
                }
            });
        }
    });
})

function pageChange() {
    $(window.parent.document).find("#attendanceImport").removeClass("active");
    $(window.parent.document).find("#attendanceStatistics").addClass("active");
}

/*
* 处理列提示
* */
function handColumnTip(value) {
    if (!value) return null;
    var span = document.createElement('span');
    span.setAttribute('title', value);
    span.innerHTML = value;
    return span.outerHTML;
}

/*************加载下拉框***********************/
function retrunIndex() {
    $("#ptype").val(GetQueryString("pcode"));
    $("#servertype").val(GetQueryString("servertype"));
    if (GetQueryStringSeachTxt("seachTxt") != null) {
        if (GetQueryStringSeachTxt("seachTxt") != "null") {
            $("#seachTxt").val(decodeURI(GetQueryStringSeachTxt("seachTxt")));
        }
    }
}

function getProjectSelect() {
    $("#ptype").html("");
    $.ajax({
        type: 'POST',
        // url: postPath + '/system/sysprjService/getProjectList',
        //根据登录用户获取对应的项目列表
        url: postPath + "/system/sysProject/getProjectToUser",
        async: false,
        data: '',
        dataType: 'json',
        success: function (result) {
            var str = "<option value=''>请选择</option>";
            if (result.success && result.data != null && result.data.length > 0) {
                for (var i = 0; i < result.data.length; i++) {
                    str += "<option value='" + (result.data[i].id || result.data[i].pcode) + "'>" + (result.data[i].name || result.data[i].pname) + "</option>";
                }
                $('select[name="pcode"]').append(str);
            }
            $("#ptype").append(str);
            $("#projectcode").html(str);
        },
        error: function () {
            // bootbox.alert("保存失败,请刷新后重试!");
        }
    });
}

function getServerType() {
    $.ajax({
        type: 'POST',
        url: postPath + '/system/sysprjService/getServerType',
        async: false,
        data: '',
        dataType: 'json',
        success: function (res) {
            if (null != res) {
                var str = "";
                var server = "<option value=''>请选择</option>";
                for (var i = 0; i < res.length; i++) {
                    str += "<label><input type='radio' name='servicetype' class='icheck' value='" + res[i].guid + "'> " + res[i].servicename + "</label>";
                    server += "<option value='" + res[i].guid + "'>" + res[i].servicename + "</option>";
                }
                $("#serverList").html(str);
                $("#servertype").html(server);
            }
        }
    });
}

function getAllDatabase() {
    console.log("already entry method of getAllDatabase")
    $("#databaseId").html("");
    $.ajax({
        type: 'POST',
        url: postPath + "/system/sysProject/getAllDatabase",
        async: false,
        data: '',
        dataType: 'json',
        success: function (cfgDbList) {
            var str = "<option value=''>请选择</option>";
            if (cfgDbList != null) {
                for (var i = 0; i < cfgDbList.length; i++) {
                    str += "<option value='" + cfgDbList[i].dbKey + "'>" + cfgDbList[i].dbName + "(" + cfgDbList[i].dbKey + ")" + "</option>";
                }
                //$('select[name="databaseId"]').append(str);
            }
            $("#databaseId").append(str);
//            $("#projectcode").html(str);
        },
        error: function () {
            bootbox.alert("保存失败,请刷新后重试!");
        }
    });
}

//选择系统下的服务
$("#ptype").change(function () {
    $("#tb_dataList").bootstrapTable('refresh');
});

/**查询条件与分页数据 */
function queryParams(pageReqeust) {
    var pcode = $("#ptype").val();
    if (!pcode) {
        $.each($("#ptype").find('option'), function (index, item) {
            pcode += $(item).attr('value') + ',';
        });
    }
    var temp = {
        order: pageReqeust.order,
        pageNo: pageReqeust.offset / pageReqeust.limit + 1,
        pageSize: pageReqeust.limit,
        seachTxt: $("#seachTxt").val(),
        pcode: pcode,
        servertype: $("#servertype").val(),
        databaseId: $("#databaseId").val()
    };
    return temp;
}

//内容初始化
function cleanContent() {
    //维护内容清空
    $("#guid").val("");
    $("#pcode").val("");
    $("#pname").val("");
    $("#ptype").val("");
    $("#pdesc").val("");
    $("#remark").val("");

    //验证信息清空
    $("#valide_pcode").html("");
    $("#valide_pname").html("");
    $("#valide_ptype").html("");
    $("#valide_pdesc").html("");
    $("#valide_remark").html("");
}

//验证表单内容
function validateData() {
    if ($("#pcode").val() == "") {
        $("#valide_pcode").html("工程编码不能为空!");
        return false;
    } else if (editStart == 1) {
        var result = false;
        $.ajax({
            type: 'POST',
            url: postPath + '/system/sysProject/valProjectPcode',
            async: false,
            data: {pcode: $("#pcode").val()},
            success: function (res) {
                if (res.success == false) {
                    $("#valide_pcode").html("工程编码已存在!");
                    return false;
                } else {
                    $("#valide_pode").html("");
                }
            }
        });

    } else {
        $("#valide_pcode").html("");
    }
    if ($("#pname").val() == "") {
        $("#valide_pname").html("工程名称不能为空!");
        return false;
    } else {
        $("#valide_pname").html("");
    }
    if ($("#ptype").val() == "") {
        $("#valide_ptype").html("请选择工程类型!");
        return false;
    } else {
        $("#valide_ptype").html("");
    }
    if ($("#pdesc").val() == "") {
        $("#valide_pdesc").html("工程说明不能为空!");
        return false;
    } else {
        $("#valide_pdesc").html("");
    }
    return true;
}

// here support multiple detele
// now test single multiple select
function deleteServerClick(row) {
    var guidList = [];
    var message  = "";
    row.forEach(function(e,i){
        guidList.push(e.guid)
        message += e.servicename + ", " + e.guid + "<br/>"
    })

    var deleteFunction = function (result) {
        if (result == false) {
            return;
        }
        var dialog = null;
        $.ajax({
            url: postPath + '/system/sysprjService/deletePrjServiceList',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(guidList),
            success: function (res) {
                $('#tb_dataList').bootstrapTable('refresh');
            },
            error: function () {
                showMsg("删除失败!", "error");
            }
        });
    };

    confirmDelete(message, deleteFunction)
}

function showMsg(text, icon) {
    $.toast({
        text: text,
        icon: icon,
        showHideTransition: 'fade',
        allowToastClose: true,
        hideAfter: 1500,
        stack: false,
        position: 'top-right',
        textAlign: 'left',
        loader: true,
        loaderBg: '#9ec600',
    });
}

function previewServerClick(servicetype, servicecode) {
    if (servicetype == "singleTableServer") {//单表服务
        window.open(postPath + "/preview/api/apiDoc_single.html?serviceUrl=" + $("#hid_serviceUrl").val() + "&serviceID=" + servicecode + "");
    } else if (servicetype == "masterConfigServer") {//主从表服务
        window.open(postPath + "/preview/MasterDetailContent.html?serviceUrl=" + $("#hid_serviceUrl").val() + "&serviceID=" + servicecode + "");
    } else if (servicetype == "executeSqlServer") {//数据脚本服务
        window.open(postPath + "/preview/api/apiDoc_sql.html?serviceUrl=" + $("#hid_serviceUrl").val() + "&serviceID=" + servicecode + "");
    } else if (servicetype == "treeconfigServer") {//资源树服务
        window.open(postPath + "/preview/ResourcesTree.html?serviceUrl=" + $("#hid_serviceUrl").val() + "&serviceID=" + servicecode + "");
    } else if (servicetype == "reportServer") {//报表服务
        window.open(postPath + "/preview/ReportServerContent.html?serviceUrl=" + $("#hid_serviceUrl").val() + "&serviceID=" + servicecode + "");
    } else if (servicetype == "tableEditServer") {//单表编辑服务
        window.open(postPath + "/preview/SingleEditContent.html?serviceUrl=" + $("#hid_serviceUrl").val() + "&serviceID=" + servicecode + "");
    } else if (servicetype == "searchServer") {//全文检索服务
        window.open(postPath + "/preview/SearchContent.html?serviceUrl=" + $("#hid_serviceUrl").val() + "&serviceID=" + servicecode + "");
    } else if (servicetype == "docSearchServer") {//文档检索服务
        window.open(postPath + "/preview/DocSearchContent.html?serviceUrl=" + $("#hid_serviceUrl").val() + "&serviceID=" + servicecode + "");
    } else if (servicetype === "moreTableServer") { // 多表跨库查询服务
        window.open(postPath + "/preview/MoreJoinTableContent.html?serviceUrl=" + $("#hid_serviceUrl").val() + "&serviceID=" + servicecode + "")
    }else if (servicetype === "polymerServer") { // 聚合查询服务
        window.open(postPath + "/preview/api/apiDoc_polymer.html?serviceUrl=" + $("#hid_serviceUrl").val() + "&serviceID=" + servicecode + "")
    }
}

//预览服务API文档
function previewAPI(servicetype, servicecode, servicename) {
    window.open(encodeURI(postPath + "/docs.html?group=" + servicetype + "&serviceID=" +
        servicecode + "&" + "servicename=" + servicename + ""));
}

//更新服务状态
function updateServerStatus(id, status) {
    var func = function (result) {
        if (result) {
            var obj = {
                "guid": id,
                "status": status
            };
            console.log(obj);
            $.ajax({
                type: 'POST',
                url: postPath + '/system/sysprjService/updatePrjService',
                async: false,
                data: JSON.stringify(obj),
                dataType: 'json',
                contentType: "application/json",
                success: function (res) {
                    console.log(res);
                    if (res) {
                        showMsg("保存成功", "success");
                        $('#tb_dataList').bootstrapTable('refresh');
                    } else {
                        showMsg("保存失败,请刷新后重试!", "error");
                    }
                }
            });
        }
    };

    var messageObj = {
        title: '提示',
        message: '是否' + (status == 1 ? '启用' : '禁用') + '服务',
        buttons: {
            confirm: {
                label: "确定"
            },
            cancel: {
                label: "取消"
            }
        },
        callback: func
    };
    bootbox.confirm(messageObj);

}


function updatepServerClick(servicetype, servicecode, pcode) {
    $.ajax({
        type: 'POST',
        url: postPath + '/system/sysprjService/getServerByGuid',
        async: false,
        data: {guid: servicetype},
        dataType: 'json',
        success: function (res) {
            if (res != null) {
                var seachTxt = $("#seachTxt").val();
                var url = encodeURI(res.pageurl + "?servercode=" + servicecode + "&servertype=" + servicetype + "&projectid=" + pcode + "&operate=edit&seachTxt=" + seachTxt);
                $(window.parent.document).find("#sysIframe").attr("src", url);
            } else {
                bootbox.alert("服务不存在!");
            }
        }
    });
}
//授权调用方
function authService(id) {
    $(window.parent.document).find("#sysIframe").attr("src", "selectApplicationCode/index" + "?id=" + id);
}

//授权调用方
function configAccessCondition(id,servicetype) {
    $(window.parent.document).find("#sysIframe").attr("src", "configApplicationCode/index" + "?id=" + id + "&servicetype=" + servicetype);
}
function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}

function GetQueryStringSeachTxt(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return r[2];
    return null;
}

function confirmDelete(message, confirmFunction){
    var messageObj = {
        title: '确认删除？',
        message: message ,
        callback: confirmFunction
    }
    bootbox.confirm(messageObj);
}
